<template>
  <view class="container">
    <view class="product-bar" v-if="productName">
      <view class="product-info">
        <text class="name">{{productName}}</text>
      </view>
    </view>
    
    <!-- 评价统计 -->
    <view class="summary-section">
      <view class="left">
        <text class="rate">{{statistics.goodRate || 0}}%</text>
        <text class="text">好评率</text>
      </view>
      <view class="right">
        <view class="tag-group">
          <view class="tag" :class="{active: currentStar === 0}" @click="switchStar(0)">全部 ({{statistics.totalCount || 0}})</view>
          <view class="tag" :class="{active: currentStar === 5}" @click="switchStar(5)">好评 ({{statistics.goodCount || 0}})</view>
          <view class="tag" :class="{active: currentStar === 3}" @click="switchStar(3)">中评 ({{statistics.mediumCount || 0}})</view>
          <view class="tag" :class="{active: currentStar === 1}" @click="switchStar(1)">差评 ({{statistics.badCount || 0}})</view>
        </view>
      </view>
    </view>
    
    <!-- 评价列表 -->
    <view class="comment-list">
      <!-- 我的评价 -->
      <view class="comment-item" v-for="(comment, index) in myComments" :key="'my-'+index" v-if="myComments.length > 0">
        <view class="user-info">
          <image class="avatar" :src="comment.memberIcon || '/static/img/default-avatar.png'" mode="aspectFill"></image>
          <text class="nickname">{{comment.memberNickName}}(我)</text>
          <view class="star">
            <text class="yticon icon-shitinghuiyuan" 
                  v-for="star in 5" 
                  :key="star" 
                  :class="{'active': star <= comment.star}">
            </text>
          </view>
        </view>
        <view class="content">{{comment.content}}</view>
        <!-- 评价图片 -->
        <view class="image-list" v-if="comment.pics">
          <image 
            v-for="(pic, picIndex) in formatPics(comment.pics)" 
            :key="picIndex" 
            :src="pic" 
            class="comment-img" 
            mode="aspectFill"
            @click="previewImage(formatPics(comment.pics), picIndex)">
          </image>
        </view>
        <view class="attr">{{comment.productAttribute}}</view>
        <view class="time">{{comment.createTime | formatTime}}</view>
        
        <!-- 商家回复 -->
        <view class="reply" v-if="comment.replayCount > 0">
          <text class="reply-title">商家回复：</text>
          <text class="reply-content">{{comment.replyContent}}</text>
          <text class="reply-time" v-if="comment.replyTime">{{comment.replyTime | formatTime}}</text>
        </view>
      </view>
      
      <!-- 其他评价 -->
      <view class="comment-item" v-for="(comment, index) in otherComments" :key="index">
        <view class="user-info">
          <image class="avatar" :src="comment.memberIcon || '/static/img/default-avatar.png'" mode="aspectFill"></image>
          <text class="nickname">{{comment.memberNickName || '匿名用户'}}</text>
          <view class="star">
            <text class="yticon icon-shitinghuiyuan" 
                  v-for="star in 5" 
                  :key="star" 
                  :class="{'active': star <= comment.star}">
            </text>
          </view>
        </view>
        <view class="content">{{comment.content}}</view>
        <!-- 评价图片 -->
        <view class="image-list" v-if="comment.pics">
          <image 
            v-for="(pic, picIndex) in formatPics(comment.pics)" 
            :key="picIndex" 
            :src="pic" 
            class="comment-img" 
            mode="aspectFill"
            @click="previewImage(formatPics(comment.pics), picIndex)">
          </image>
        </view>
        <view class="attr">{{comment.productAttribute}}</view>
        <view class="time">{{comment.createTime | formatTime}}</view>
        
        <!-- 商家回复 -->
        <view class="reply" v-if="comment.replayCount > 0">
          <text class="reply-title">商家回复：</text>
          <text class="reply-content">{{comment.replyContent}}</text>
          <text class="reply-time" v-if="comment.replyTime">{{comment.replyTime | formatTime}}</text>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty" v-if="myComments.length === 0 && otherComments.length === 0">
        <text class="empty-text">暂无评价</text>
      </view>
      
      <!-- 加载更多 -->
      <uni-load-more :status="loadingType"></uni-load-more>
    </view>
  </view>
</template>

<script>
  import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
  import { getProductComments, getCommentStatistics } from '@/api/comment.js';
  import { formatDate } from '@/utils/date';
  
  export default {
    components: {
      uniLoadMore
    },
    data() {
      return {
        productId: null,
        productName: '',
        currentStar: 0,
        myComments: [],
        otherComments: [],
        statistics: {
          totalCount: 0,
          goodCount: 0,
          mediumCount: 0,
          badCount: 0,
          goodRate: 0,
          isLogin: false
        },
        total: 0,
        pageSize: 10,
        pageNum: 1,
        loading: false,
        loadingType: 'more',
        isLogin: false
      }
    },
    onLoad(options) {
      if (options.productId) {
        this.productId = options.productId;
      }
      if (options.productName) {
        this.productName = decodeURIComponent(options.productName);
      }
      
      // 加载评论统计信息
      this.loadCommentStatistics();
      // 加载评论列表
      this.loadComments();
    },
    onReachBottom() {
      if (this.loadingType === 'noMore') return;
      this.pageNum++;
      this.loadComments();
    },
    onPullDownRefresh() {
      this.pageNum = 1;
      // 刷新时重新加载统计信息
      this.loadCommentStatistics();
      this.loadComments('refresh');
    },
    filters: {
      formatTime(time) {
        if (!time) return '';
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm');
      }
    },
    methods: {
      // 加载评论统计信息
      loadCommentStatistics() {
        if (!this.productId) return;
        
        getCommentStatistics(this.productId).then(response => {
          if (response.code === 200 && response.data) {
            this.statistics = response.data;
            this.total = this.statistics.totalCount || 0;
            this.isLogin = this.statistics.isLogin || false;
          }
        }).catch(error => {
          console.error('获取评论统计信息失败:', error);
        });
      },
      
      // 加载评价数据
      loadComments(type = '') {
        if (this.loading) return;
        this.loading = true;
        
        if (type === 'refresh') {
          uni.showLoading({
            title: '刷新中...'
          });
        }
        
        getProductComments(this.productId, this.pageSize, this.pageNum, this.currentStar).then(response => {
          this.loading = false;
          
          if (type === 'refresh') {
            uni.hideLoading();
            uni.stopPullDownRefresh();
          }
          
          if (response.code === 200 && response.data) {
            // 处理登录状态
            if (response.data.hasOwnProperty('isLogin')) {
              this.isLogin = response.data.isLogin;
            }
            
            // 处理我的评价 - 只在第一页或刷新时设置
            if ((this.pageNum === 1 || type === 'refresh') && response.data.myComments) {
              this.myComments = response.data.myComments || [];
            }
            
            // 处理评论列表数据
            if (response.data.list) {
              // 直接使用返回的list数据
              let commentList = response.data.list || [];
              this.total = response.data.total || 0;
              
              // 如果有我的评价，需要过滤掉重复的评论
              if (this.myComments.length > 0) {
                const myCommentIds = this.myComments.map(comment => comment.id);
                const filteredComments = commentList.filter(comment => !myCommentIds.includes(comment.id));
                
                // 更新评论列表
                if (this.pageNum === 1 || type === 'refresh') {
                  this.otherComments = filteredComments;
                } else {
                  this.otherComments = [...this.otherComments, ...filteredComments];
                }
              } else {
                // 没有我的评价，直接使用评论列表
                if (this.pageNum === 1 || type === 'refresh') {
                  this.otherComments = commentList;
                } else {
                  this.otherComments = [...this.otherComments, ...commentList];
                }
              }
              
              // 设置加载状态 - 考虑筛选后的评论数量
              const totalFilteredComments = this.myComments.length + this.otherComments.length;
              if (totalFilteredComments >= this.total || commentList.length === 0) {
                this.loadingType = 'noMore';
              } else {
                this.loadingType = 'more';
              }
            } 
            // 兼容旧的数据结构
            else if (response.data.pageInfo) {
              const pageInfo = response.data.pageInfo;
              this.total = pageInfo.total;
              
              // 从otherComments或pageInfo.list获取评论数据
              let otherComments = response.data.otherComments || [];
              
              // 如果otherComments为空，则使用pageInfo.list，但需要过滤掉已经在myComments中的评论
              if (otherComments.length === 0 && pageInfo.list && pageInfo.list.length > 0) {
                // 获取myComments中所有评论ID
                const myCommentIds = this.myComments.map(comment => comment.id);
                
                // 从pageInfo.list中过滤掉与myComments中ID相同的评论
                otherComments = pageInfo.list.filter(comment => !myCommentIds.includes(comment.id));
              }
              
              // 更新评论列表，根据是第一页还是加载更多来处理
              if (this.pageNum === 1 || type === 'refresh') {
                this.otherComments = otherComments;
              } else {
                this.otherComments = [...this.otherComments, ...otherComments];
              }
              
              // 设置加载状态 - 考虑myComments和otherComments的总数
              if ((this.myComments.length + this.otherComments.length) >= pageInfo.total) {
                this.loadingType = 'noMore';
              } else {
                this.loadingType = 'more';
              }
            }
          } else {
            uni.showToast({
              title: response.message || '获取评价失败',
              icon: 'none'
            });
          }
        }).catch(error => {
          console.error('获取评价失败:', error);
          this.loading = false;
          
          if (type === 'refresh') {
            uni.hideLoading();
            uni.stopPullDownRefresh();
          }
          
          uni.showToast({
            title: '获取评价失败',
            icon: 'none'
          });
        });
      },
      
      // 切换星级筛选
      switchStar(star) {
        if (this.currentStar === star) return;
        this.currentStar = star;
        this.pageNum = 1;
        this.myComments = []; // 重置我的评价列表
        this.otherComments = []; // 重置其他评价列表
        this.loadingType = 'more';
        this.loadComments('refresh');
      },
      
      // 格式化图片地址
      formatPics(pics) {
        if (!pics) return [];
        if (typeof pics === 'string') {
          return pics.split(',').filter(pic => pic && pic.trim() !== '');
        }
        return Array.isArray(pics) ? pics : [];
      },
      
      // 预览图片
      previewImage(pics, current) {
        if (!pics || !pics.length) return;
        uni.previewImage({
          urls: pics,
          current: pics[current]
        });
      }
    }
  }
</script>

<style lang="scss">
  .container {
    padding-bottom: 20rpx;
    background-color: #f8f8f8;
    min-height: 100vh;
  }
  
  .product-bar {
    background-color: #fff;
    padding: 20rpx 30rpx;
    margin-bottom: 20rpx;
    
    .product-info {
      .name {
        font-size: 28rpx;
        color: #333;
      }
    }
  }
  
  .summary-section {
    display: flex;
    align-items: center;
    background-color: #fff;
    padding: 30rpx;
    margin-bottom: 20rpx;
    
    .left {
      flex: 0 0 120rpx;
      text-align: center;
      margin-right: 30rpx;
      
      .rate {
        font-size: 48rpx;
        color: #f04c41;
        font-weight: bold;
        display: block;
      }
      
      .text {
        font-size: 24rpx;
        color: #888;
      }
    }
    
    .right {
      flex: 1;
      
      .tag-group {
        display: flex;
        flex-wrap: wrap;
        
        .tag {
          padding: 10rpx 20rpx;
          background-color: #f5f5f5;
          margin-right: 20rpx;
          margin-bottom: 20rpx;
          border-radius: 30rpx;
          font-size: 24rpx;
          color: #666;
          
          &.active {
            background-color: #f04c41;
            color: #fff;
          }
        }
      }
    }
  }
  
  .comment-list {
    padding: 0 30rpx;
    
    .comment-item {
      background-color: #fff;
      padding: 30rpx;
      margin-bottom: 20rpx;
      border-radius: 10rpx;
      
      .user-info {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;
        
        .avatar {
          width: 60rpx;
          height: 60rpx;
          border-radius: 50%;
          margin-right: 20rpx;
        }
        
        .nickname {
          font-size: 28rpx;
          color: #333;
          margin-right: 20rpx;
        }
        
        .star {
          display: flex;
          
          .yticon {
            font-size: 24rpx;
            color: #ddd;
            margin-right: 5rpx;
            
            &.active {
              color: #ffb400;
            }
          }
        }
      }
      
      .content {
        font-size: 28rpx;
        color: #333;
        line-height: 1.5;
        margin-bottom: 20rpx;
      }
      
      .image-list {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 20rpx;
        
        .comment-img {
          width: 160rpx;
          height: 160rpx;
          margin-right: 20rpx;
          margin-bottom: 20rpx;
          border-radius: 8rpx;
        }
      }
      
      .attr {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 10rpx;
      }
      
      .time {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 20rpx;
      }
      
      .reply {
        background-color: #f8f8f8;
        padding: 20rpx;
        border-radius: 8rpx;
        
        .reply-title {
          font-size: 24rpx;
          color: #666;
          font-weight: bold;
        }
        
        .reply-content {
          font-size: 24rpx;
          color: #666;
          line-height: 1.5;
        }
        
        .reply-time {
          font-size: 22rpx;
          color: #999;
          margin-top: 10rpx;
        }
      }
    }
    
    .empty {
      padding: 100rpx 0;
      text-align: center;
      
      .empty-text {
        font-size: 28rpx;
        color: #999;
      }
    }
  }
</style> 